package com.test.transactional.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

/**
 * @Description: 根据 X-BIZ-ID 切换数据库
 **/
@Slf4j
@Component
public class DynamicRoutingSourceFilter implements Filter {

    @Autowired
    private DataSourceProperties dataSourceProperties;
    @Autowired
    private DataSource dataSource;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        HttpServletRequest request  = (HttpServletRequest) servletRequest;
        log.info("DynamicRoutingSourceFilter, requestUrl:{}", request.getRequestURL());
        String bizId= request.getHeader("X-BIZ-ID");
        if(!StringUtils.isEmpty(bizId)){
            DynamicRoutingDataSource dynamicRoutingDataSource = (DynamicRoutingDataSource) dataSource;
            String key = "db_" + bizId;
            if(!dynamicRoutingDataSource.getDataSources().containsKey(key)){
                /**
                 * 如果该数据源不存在则创建新的数据源
                 */
                String url = dataSourceProperties.getUrl().replace("demo1", bizId);
                DruidDataSource druidDataSource = new DruidDataSource();
                druidDataSource.setUrl(url);
                druidDataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
                druidDataSource.setUsername(dataSourceProperties.getUsername());
                druidDataSource.setPassword(dataSourceProperties.getPassword());
                dynamicRoutingDataSource.addDataSource(key, druidDataSource);
            }
            DynamicDataSourceContextHolder.push(key);
        } else {
            DynamicDataSourceContextHolder.push("master");
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
